import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/favorites_provider.dart';
import '../widgets/product_card.dart';

class FavoritesPage extends StatelessWidget {
  const FavoritesPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Consumer<FavoritesProvider>(builder: (context, favs, _) {
      final ids = favs.ids.toList();
      if (ids.isEmpty) {
        return Scaffold(
          appBar: AppBar(title: const Text('收藏')),
          body: Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: const [
                Icon(Icons.favorite_border, size: 64),
                SizedBox(height: 12),
                Text('暂无收藏，去逛逛吧～'),
              ],
            ),
          ),
        );
      }
      return Scaffold(
        appBar: AppBar(title: const Text('收藏')),
        body: ListView.builder(
          itemCount: ids.length,
          itemBuilder: (ctx, i) {
            final id = ids[i];
            final item = favs.items.firstWhere((p) => p.id == id, orElse: () => null as dynamic);
            if (item != null) {
              return ProductCard(product: item);
            }
            return FutureBuilder(
              future: favs.ensureItem(id),
              builder: (ctx, snap) {
                if (snap.connectionState == ConnectionState.waiting) {
                  return const Padding(
                    padding: EdgeInsets.all(16),
                    child: Center(child: CircularProgressIndicator()),
                  );
                }
                final p = snap.data;
                if (p == null) {
                  return ListTile(
                    title: Text('商品 #$id 加载失败'),
                    trailing: IconButton(icon: const Icon(Icons.delete), onPressed: () => favs.remove(id)),
                  );
                }
                return ProductCard(product: p);
              },
            );
          },
        ),
      );
    });
  }
}